import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.IOException;

/**
 * Created by Ay on 2016/7/27.
 */
public class FreeMarkerTemplateUtils {

    private FreeMarkerTemplateUtils(){}
    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

    static{
        //这里比较重要，用来指定加载模板所在的路径
        try {
//            CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/ftl"));
//            CONFIGURATION.setDirectoryForTemplateLoading(new File("D:\\projectCodeing\\fremark\\src\\ftl\\"));
            CONFIGURATION.setDirectoryForTemplateLoading(new File("D:\\projectCodeing\\fremark\\src\\ftl-vshop\\"));
            CONFIGURATION.setObjectWrapper(new DefaultObjectWrapper()) ;
            CONFIGURATION.setDefaultEncoding("UTF-8");
            CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Template getTemplate(String templateName) throws IOException {
        try {
            Template template = CONFIGURATION.getTemplate(templateName);
            return template;
        } catch (IOException e) {
            throw e;
        }
    }

    public static void clearCache() {
        CONFIGURATION.clearTemplateCache();
    }
}